/**   
 *    
 * 项目名称：SmartKungFu   
 * 类名称：MstRoleController   
 * 类描述：角色控制层   
 * 创建人：zhangl  
 * 创建时间：2016年10月12日 上午10:31:33   
 * 修改人：zhangl   
 * 修改时间：2016年10月12日 上午10:31:33   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.github.miemiedev.mybatis.paginator.domain.Paginator;
import com.lst.common.BaseController;
import com.lst.common.CommonEnum;
import com.lst.exception.MyException;
import com.lst.model.FolPara;
import com.lst.model.MstButton;
import com.lst.model.MstRole;
import com.lst.model.MstUser;
import com.lst.model.UserRole;
import com.lst.service.MstButtonService;
import com.lst.service.MstRoleService;
import com.lst.service.UserRoleService;
import com.lst.utils.CommonUtils;
import com.lst.utils.DateUtil;

/**
 * @ClassName: MstRoleController
 * @Description: 角色控制层
 * @author zhangl
 * @date 2016年10月12日 上午10:31:33
 *
 */
@Controller
@RequestMapping("mstRoleController")
public class MstRoleController extends BaseController {

	@Autowired
	private MstRoleService mstRoleService;

	@Autowired
	private MstButtonService mstButtonService;

	@Autowired
	private UserRoleService userRoleService;	

	/**
	 * 
	 * @Title: list
	 * @Description:页面加载
	 * @param @param request
	 * @param @param response
	 * @param @param menuId
	 * @param @param page
	 * @param @param rows
	 * @param @param index_exp
	 * @param @param index_che
	 * @param @param rolName
	 * @param @return
	 * @param @throws MyException    设定文件
	 * @return ModelAndView    返回类型
	 */
	@RequestMapping(value = "/list")
	public ModelAndView list(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(required = true) int menuId,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGE) int page,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGESIZE) int rows,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che,
			@RequestParam(required = false,defaultValue = "") String rolName) throws MyException {
		Date startDate = new Date();
		logger.info("list begin: " + startDate);

		FolPara folPara = new FolPara();
		folPara.setMenuId(menuId);
		folPara.setPage(page);
		folPara.setRows(rows);
		folPara.setRolName(rolName);

		MstUser mstUser = this.getMySession().getMstUser();
		List<MstButton> btns = CommonUtils.readPermissionWithBtn(menuId, mstUser, mstButtonService);

		ModelAndView mv = new ModelAndView(CommonEnum.FORWARD_VIEW_MAIN_SYSTEM + "role_list");
		mv.addObject("btns", btns);
		mv.addObject("folPara",folPara);

		mv.addObject("MENU_STYLE_INDEX_EXP", index_exp);
		mv.addObject("MENU_STYLE_INDEX_CHE", index_che);

		logger.info("list end run(s): " + DateUtil.calLastedTime(startDate));

		return mv;
	}

	/**
	 * 
	 * @Title: queryList
	 * @Description:queryList
	 * @param @param page
	 * @param @param pageSize
	 * @param @param rolName
	 * @param @return
	 * @param @throws MyException    设定文件
	 * @return Object    返回类型
	 */
	@RequestMapping(value = "/queryList")
	@ResponseBody
	public Object queryList(
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGE) Integer page,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGESIZE) Integer pageSize,
			@RequestParam(required = false,defaultValue = "")String sort,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEM_ORDER_DESC)String order,
			@RequestParam(required = false,defaultValue = "")String rolName) throws MyException {
		Date startDate = new Date();
		logger.info("queryList begin: " + startDate);

		Map<String, Object> datMap = new HashMap<String,Object>();
		datMap.put("isDeleted", 0);
		//datMap.put("enabled", 1);
		if(StringUtils.isEmpty(sort)){
			datMap.put("orderByClause","r.createdate desc");
		} else{
			datMap.put("orderByClause",sort + " " + order);
		}

		if(!StringUtils.isBlank(rolName)){
			datMap.put("_rolName", rolName.trim());
		}

		PageBounds pageBounds = new PageBounds(page, pageSize);
		List<MstRole> list = mstRoleService.queryByList(datMap, pageBounds);

		PageList<MstRole> pageList = (PageList<MstRole>) list;
		Paginator paginator = pageList.getPaginator();

		HashMap<String, Object> indexPages = new HashMap<String, Object>();
		indexPages.put("total", paginator.getTotalCount());	
		indexPages.put("rows", list);

		logger.info("queryList end run(s): " + DateUtil.calLastedTime(startDate));

		return indexPages;
	}

	/**
	 * 	
	 * @Title: edit
	 * @Description:编辑页面
	 * @param @param id
	 * @param @param index_exp
	 * @param @param index_che
	 * @param @return    设定文件
	 * @return ModelAndView    返回类型
	 */
	@RequestMapping(value = "/edit")
	public ModelAndView edit(
			@RequestParam(required = false) String id,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che) {
		Date startDate = new Date();
		logger.info("edit begin: " + startDate);

		ModelAndView mv = new ModelAndView(CommonEnum.FORWARD_VIEW_MAIN_SYSTEM + "role_edit");

		if (!StringUtils.isBlank(id)) {
			MstRole mstRole = mstRoleService.selectByPrimaryKey(Integer.parseInt(id));
			mv.addObject("mstRole", mstRole);
		}


		mv.addObject("MENU_STYLE_INDEX_EXP", index_exp);
		mv.addObject("MENU_STYLE_INDEX_CHE", index_che);

		logger.info("edit end run(s): " + DateUtil.calLastedTime(startDate));

		return mv;
	}

	/**
	 * 
	 * @Title: save
	 * @Description:save
	 * @param @param mstrole
	 * @param @param folPara
	 * @param @return
	 * @param @throws MyException    设定文件
	 * @return String    返回类型
	 */
	@RequestMapping(value = "/save",method = RequestMethod.POST)
	public String save(MstRole mstrole,FolPara folPara) throws MyException {
		Date startDate = new Date();
		logger.info("save begin: " + startDate);

		MstUser mstUser = this.getMySession().getMstUser();

		if (mstrole.getId() != null) {
			mstrole.setUpdatedate(startDate);
			mstrole.setUpdateuser(mstUser.getId());

			mstRoleService.updateByPrimaryKeySelective(mstrole);
		} else {
			mstrole.setIsdeleted(false);
			mstrole.setCreatedate(startDate);
			mstrole.setCreateuser(mstUser.getId());

			mstRoleService.insert(mstrole);
		}

		StringBuffer sb = new StringBuffer("?");
		sb.append("menuId=" + folPara.getMenuId());
		sb.append("&page=" + folPara.getPage());
		sb.append("&pageSize=" + folPara.getPageSize());
		sb.append("&rolName=" + folPara.getRolName());
		
		sb.append("&index_exp=" + folPara.getIndex_exp());
		sb.append("&index_che=" + folPara.getIndex_che());

		logger.info("save end run(s):" + DateUtil.calLastedTime(startDate));

		return "redirect:list" + sb.toString();
	}

	/**
	 * 
	 * @Title: isUnique
	 * @Description: 验证属性唯一性
	 * @param @param property 
	 * @param @param id
	 * @param @return    设定文件
	 * @return Boolean    返回类型
	 */
	@RequestMapping(value = "/isUnique",method = RequestMethod.GET)
	@ResponseBody
	public Boolean isUnique(
			@RequestParam(required = true)String property,
			@RequestParam(required = false,defaultValue = "")String id){
		Date startDate = new Date();
		logger.info("isUnique begin: " + startDate);

		boolean flag = false;

		Map<String, Object> reqMap = new HashMap<String,Object>();
		reqMap.put("enabled", 1);
		reqMap.put("isDeleted", 0);
		reqMap.put("rolNo", property);

		List<MstRole> roles= mstRoleService.queryByList(reqMap, new PageBounds());

		if(roles.isEmpty()) flag = true;

		else{
			if(!StringUtils.isBlank(id)){//当为编辑操作时，存在唯一一个相同的名称名，验证通过
				if(roles.get(0).getId().equals(Integer.valueOf(id))){
					flag = true;
				}
			}
		}
		logger.info("isUnique end run(s): " 
				+ DateUtil.calLastedTime(startDate));

		return flag;
	}

	/**
	 * 
	 * @Title: initRoleWithUser
	 * @Description: 用户及角色信息加载（包括角色和菜单信息）
	 * @param @param userId
	 * @param @return    设定文件
	 * @return List<MstRole>    返回类型
	 */
	@RequestMapping(value = "initRoleWithUser",method = RequestMethod.GET)
	@ResponseBody
	public List<MstRole> initRoleWithUser(@RequestParam(required = true)Integer userId){
		Date startDate = new Date();
		logger.info("initRoleWithUser begin: " + startDate);

		List<MstRole> roles = null;

		Map<String, Object> rolMap = new HashMap<String,Object>();
		rolMap.put("enabled", 1);
		rolMap.put("isDeleted", 0);
		rolMap.put("orderByClause", "r.id asc");
		rolMap.put("rolType", CommonEnum.SYSCODE_USERTYPE_WEB);

		Map<String, Object> grMap = new HashMap<String,Object>();
		grMap.put("enabled", 1);
		grMap.put("isDeleted", 0);
		grMap.put("userId", userId);

		PageBounds pageBounds = new PageBounds();

		try {
			//读取角色，以及角色拥有的权限列表
			//roles = mstroleService.queryListForRoleAndPer();
			//读取角色，不包含权限
			roles = mstRoleService.queryByList(rolMap, pageBounds);
			if(userId != null){
				//读取用户拥有的角色
				List<UserRole> urs = userRoleService.queryByList(grMap, pageBounds);
				//标记用户拥有的角色
				for(MstRole role : roles ){
					for(UserRole ur : urs){
						if(role.getId().equals(ur.getRolid())){
							role.setFlag(true);
							break;
						}else{
							role.setFlag(false);
						}
					}
				}
			}

		} catch (Exception e) {
			logger.error("initRoleWithUser error: " ,e);
		}

		logger.info("initRoleWithUser end: "
				+ DateUtil.calLastedTime(startDate));

		return roles;
	}

	/**
	 * 
	 * @Title: delList
	 * @Description: 批量删除
	 * @param @param request
	 * @param @param response
	 * @param @param ids
	 * @param @return
	 * @param @throws MyException    设定文件
	 * @return boolean    返回类型
	 */
	@RequestMapping("delList")
	@ResponseBody
	public boolean delList(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(required = true) String ids) throws MyException {
		Date startDate = new Date();
		logger.info("delList begin: " + startDate);

		boolean flag = false;

		MstUser mstUser = this.getMySession().getMstUser();

		Map<String, Object> reqMap = new HashMap<String,Object>();
		reqMap.put("ids", ids);
		reqMap.put("updateUser", mstUser.getId());

		try {
			mstRoleService.delList(reqMap);
			flag = true;
		} catch (Exception e) {
			logger.error("delList error: " ,e);
		}

		logger.info("delList end run(s): " + DateUtil.calLastedTime(startDate));

		return flag;
	}
}
